package entityManager

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntityManager"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisService"
	"gitee.com/fierce_wolf/go-fox-edge-common/commSql"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeTSQL"
	_ "github.com/go-sql-driver/mysql" //具体使用的时候，请在服务中，某个go文件中import这一句话
	_ "github.com/mattn/go-sqlite3"    //具体使用的时候，请在服务中，某个go文件中import这一句话
)

func Instance() {
	producer := commRedisService.IRedisManager.GetRedisProducer()
	consumer := commRedisService.IRedisManager.GetRedisConsumer()
	reader := commRedisService.IRedisManager.GetRedisReader()
	writer := commRedisService.IRedisManager.GetRedisWriter()

	producer[edgeEntity.Type.DeviceObjInfEntity.Type()] = nil
	producer[edgeEntity.Type.DeviceStatusEntity.Type()] = nil

	consumer[edgeEntity.Type.ConfigEntity.Type()] = nil
	consumer[edgeEntity.Type.DeviceMapperEntity.Type()] = nil
	consumer[edgeEntity.Type.DeviceEntity.Type()] = nil

	reader[edgeEntity.Type.DeviceValueEntity.Type()] = nil
	writer[edgeEntity.Type.DeviceValueEntity.Type()] = nil

	// 初始化数据库的字典
	for key := range consumer {
		commSql.Register(key)
	}
	for key := range producer {
		commSql.Register(key)
	}
	commSql.Register(edgeEntity.Type.DeviceObjectEntity.Type())
	commSql.Register(edgeEntity.Type.DeviceRecordEntity.Type())
	commSql.Register(edgeEntity.Type.DeviceHistoryEntity.Type())
	commSql.Register(edgeEntity.Type.DeviceValueRecordEntity.Type())
	commSql.Register(edgeEntity.Type.DeviceSequenceEntity.Type())
}

func InitLoadEntity() {
	// 初始化MYSQL/SQLite的数据库连接
	initDBConnect()

	commEntityManager.InitLoadEntity()
}

// Scheduler 线程函数
func Scheduler() {
	commEntityManager.Scheduler()
}

func initDBConnect() {
	// 连接MYSQL数据库
	if commSql.GetDBType() == "mysql" {
		if err := commSql.Client.ConnectMySQL(); err != nil {
			panic("连接数据库失败:" + err.Error())
		}

		edgeTSQL.API = &edgeTSQL.MySQL{}
		return
	}

	// 连接SQLite3数据库
	if commSql.GetDBType() == "sqlite3" {
		// 打开数据库
		if err := commSql.Client.ConnectSQLite("fox-edge.db"); err != nil {
			panic("连接数据库失败:" + err.Error())
		}

		// 打开时序数据库
		if err := edgeTSQL.Client.ConnectSQLite("fox-edge-ts.db"); err != nil {
			panic("连接数据库失败:" + err.Error())
		}

		edgeTSQL.API = &edgeTSQL.SQLite3{}
		return
	}
}
